from logging.config import fileConfig
import os
from dotenv import load_dotenv
from sqlalchemy import engine_from_config  # 同步引擎创建
from sqlalchemy import pool
from alembic import context

# 加载 .env 文件（路径不变）
env_path = os.path.join(os.path.dirname(__file__), "../../.env")
load_dotenv(env_path)

# 导入同步版 Base（现在 database.py 是同步的了）
from user_service.database import Base
target_metadata = Base.metadata

# 读取数据库配置（不变）
config = context.config
section = config.config_ini_section
config.set_section_option(section, "MYSQL_USER", os.getenv("MYSQL_USER"))
config.set_section_option(section, "MYSQL_PASSWORD", os.getenv("MYSQL_PASSWORD"))
config.set_section_option(section, "MYSQL_HOST", os.getenv("MYSQL_HOST"))
config.set_section_option(section, "MYSQL_PORT", os.getenv("MYSQL_PORT", "3306"))
config.set_section_option(section, "MYSQL_DB_USER", os.getenv("MYSQL_DB_USER"))

# 日志配置（不变）
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

# ------------------------------
# 纯同步迁移逻辑（无任何 async）
# ------------------------------
def run_migrations_offline() -> None:
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )
    with context.begin_transaction():
        context.run_migrations()

def run_migrations_online() -> None:
    # 同步引擎创建（关键：用 engine_from_config）
    connectable = engine_from_config(
        config.get_section(config.config_ini_section, {}),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    # 同步连接（无 async with）
    with connectable.connect() as connection:
        context.configure(
            connection=connection, target_metadata=target_metadata
        )
        with context.begin_transaction():
            context.run_migrations()

# 执行迁移（不变）
if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()